import Fetch from 'isomorphic-fetch';
import Promise from 'bluebird';

const apiPrefix = '//tong.yixinonline.com/api';

const fetch = (url, { headers, query, params, body, method } = {}) => {
  return new Promise( (resolve, reject) => {
    url = `${apiPrefix}${url}`;

    if(typeof params === 'object') {
      Object.keys(params).map(k => url.replace(':' + k, params[k]));
    }

    if(typeof query === 'object') {
      url += '?'
      Object.keys(query).map( k => url += `${k}=${query[k]}&`)
    }

    const options = {};
    if(typeof headers === 'object') {
      options.headers = headers;
    }

    method = method ? method.toUpperCase() : 'GET';

    if(typeof body === 'object') {
      if(method === 'GET' || method === 'OPTIONS') {
        return reject(new TypeError('GET or OPTIONS request can not attach data.'))
      }
      try {
        options.body = JSON.stringify(body)
      } catch(e) {
        return reject(new TypeError(e));
      }
    }

    options.method = method;

    Fetch(url, options)
    .then( resp => {
      if(resp.status >= 200 && resp.status < 300) {
        return resp.json();
      } else {
        return reject(new Error(resp))
      }
    })
    .then( json => {
      resolve(json);
    })
    .catch(e => {
      return reject(e);
    });
  })
}

export default fetch;
